package com.cykj.service.impl;

import com.cykj.dto.ResponseDTO;
import com.cykj.entity.UserDO;
import com.cykj.mapper.UserMapper;
import com.cykj.service.IUserService;
import com.cykj.utils.JwtUtil;
import com.cykj.utils.MD5Util;
import com.cykj.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 王宇
 * @CreateTime: 2025-07-22  16:43
 * @BelongsProject: jd_seckill
 * @BelongsPackage: com.cykj.service
 * @description 用户服务接口实现
 */
@Service
public class IUserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseDTO login(UserVO userVO) {
        // 判断该用户是否被封禁
        Integer isBaned = userMapper.accIsBaned(userVO);
        if (isBaned != null && isBaned == 1) {
            return ResponseDTO.error("该账号已被封禁");
        }

        // 判断该用户账号密码是否对应
        userVO.setUserPassword(MD5Util.encrypt(userVO.getUserPassword()));
        UserDO userDO = userMapper.login(userVO);
        if (userDO != null) {
            // 根据用户id，用户昵称生成token
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("userId", userDO.getUserId());
            hashMap.put("userName", userDO.getUserName());
            String token = JwtUtil.generateJwt(hashMap);
            hashMap.put("token", token);

            // token存入redis里，30分钟有效期，之后每携带token请求一次就更新有效期，最多持续到token有效期
            redisTemplate.opsForValue().set(token, userDO, 30, TimeUnit.MINUTES);
            return ResponseDTO.success("登录成功", hashMap);
        }
        return ResponseDTO.error("账号或密码错误");
    }

    @Override
    public ResponseDTO register(UserVO userVO) {
        // 判断该账号是否已经被注册
        Integer isEnrolled = userMapper.accIsEnrolled(userVO);
        if (isEnrolled != null && isEnrolled == 1) {
            return ResponseDTO.error("该账号已被注册");
        }

        // 用户进行注册
        userVO.setUserPassword(MD5Util.encrypt(userVO.getUserPassword()));
        Integer enroll = userMapper.register(userVO);
        if (enroll != null && enroll == 1) {
            return ResponseDTO.success("注册成功");
        }
        return ResponseDTO.error("注册失败");
    }
}
